namespace umbracoUtilities
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Collections;
	using System.Web;
	using System.Web.UI;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;

	/// <summary>
	///		Summary description for umbInputOutput.
	/// </summary>
	public partial class AutoForm : System.Web.UI.UserControl
	{

		private ArrayList _dataFields = new ArrayList();
		protected System.Web.UI.WebControls.TextBox Title = new TextBox();

		private int _nodeTypeId;
		private string _tabName = "";
		private int _nodeId = -1;
		private bool _editMode = false;
		private bool _showTitle = true;
		private string _titleName = "Title";
		private string _thanks = "#thanks";
		private bool _publish = true;
		private bool _showDescription = false;
		private string _saveMemberIdAlias = "";
		private bool enableClientScript = false;
		private bool _refreshToParent = false;
		private int _userId = 0;
		private string _storeInCookie = "";

		[umbraco.cms.businesslogic.macro.MacroComment("Choose the Document type that you wish to be created")]
		public int DocumentType 
		{
			set {_nodeTypeId = value;}
		}
		public string TabName 
		{
			set {_tabName = value;}
		}
		public int ChooseWhereToStore 
		{
			set {_nodeId = value;}
		}
		public bool EditMode 
		{
			set {_editMode = value;}
		}
		public bool ShowTitle 
		{
			set {_showTitle = value;}
		}
		public string TitleName 
		{
			set {_titleName = value;}
		}
		public string SaveMemberAlias 
		{
			set {_saveMemberIdAlias = value;}
		}
		public bool ShowDescriptions 
		{
			set {_showDescription = value;}
		}
		public string SubmitButtonText 
		{
			set {Button1.Text = value;}
		}
		public string TextOnSubmit 
		{
			set {_thanks = value;}
		}
		public bool PublishOnSubmit 
		{
			set {_publish = value;}
		}
		public bool RefreshToParent 
		{
			set {_refreshToParent = value;}
		}
		public int PublishWithUserId 
		{
			set {_userId = value;}
		}
		public string StorePropertiesInCookies 
		{
			set {_storeInCookie = value;}
		}

		protected void Page_Load(object sender, System.EventArgs e)
		{
			if (_thanks.Length > 1) 
			{
				if (_thanks.StartsWith("#")) 
				{
					LiteralThanks.Text =  umbraco.library.GetDictionaryItem(_thanks.Remove(0,1));
				}
				else
					LiteralThanks.Text = _thanks;
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);

			umbraco.cms.businesslogic.web.Document d = null;
			if (_nodeId > 0)
				d = new umbraco.cms.businesslogic.web.Document(_nodeId);

			// Title
			if (_showTitle) 
			{
				if (d != null && _editMode)
					Title.Text = d.Text;

				Title.CssClass = "umbracoAutoFormTitleInput";
				Title.ID = "Title";

				PHEditFields.Controls.Add(new LiteralControl("<p><label for=\"" + Title.ClientID + "\">" + _titleName + ": </label>"));
				PHEditFields.Controls.Add(Title);
				System.Web.UI.WebControls.RequiredFieldValidator rq = new RequiredFieldValidator();
				rq.ControlToValidate = Title.ID;
				rq.EnableClientScript = enableClientScript;
				rq.Display = System.Web.UI.WebControls.ValidatorDisplay.Dynamic;
				rq.CssClass = "umbracoAutoFormAlert";
				string[] errorVars = {"Title", ""};
				rq.ErrorMessage = "<br/>" + umbraco.ui.Text("errorHandling", "errorMandatoryWithoutTab", errorVars, null);
				PHEditFields.Controls.Add(rq);
				PHEditFields.Controls.Add(new LiteralControl("</p>"));       
         
			}

			string userControlId = PanelInput.Parent.ClientID + "_";
			foreach (umbraco.cms.businesslogic.ContentType.TabI t in new umbraco.cms.businesslogic.web.DocumentType(_nodeTypeId).getVirtualTabs) 
			{
				if ((","+_tabName+",").IndexOf(","+t.Caption.ToLower()+",") > -1)
				{
					foreach (umbraco.cms.businesslogic.propertytype.PropertyType pt in t.PropertyTypes) 
					{
						umbraco.interfaces.IDataType dt = pt.DataTypeDefinition.DataType;
						dt.DataEditor.Editor.ID = pt.Alias;

						umbraco.interfaces.IData df = pt.DataTypeDefinition.DataType.Data;
						if (_nodeId > 0 && _editMode)
						{
							dt.Data.PropertyId = d.getProperty(pt).Id;

							if (!IsPostBack) 
								dt.Data.Value = d.getProperty(pt.Alias).Value;
						} 
						else if (!IsPostBack) 
						{
							dt.Data.Value = "";

							// Check for cookie info
							if (System.Web.HttpContext.Current.Request.Cookies["umbAutoform_"+pt.Alias] != null) {
								if (System.Web.HttpContext.Current.Request.Cookies["umbAutoform_"+pt.Alias].Value != "") 
								{
									dt.Data.Value = System.Web.HttpContext.Current.Request.Cookies["umbAutoform_"+pt.Alias].Value;
								}
							}
						}

						((Control) dt.DataEditor.Editor).ID = pt.Alias;
						_dataFields.Add(dt);
						PHEditFields.Controls.Add(new LiteralControl("<p><label for=\"" + userControlId +  ((Control)dt.DataEditor.Editor).ClientID +"\">" + pt.Name + ":</label>"));
						PHEditFields.Controls.Add((Control)dt.DataEditor.Editor);

						// Validation
						if (pt.Mandatory) 
						{
							try 
							{
								System.Web.UI.WebControls.RequiredFieldValidator rq = new RequiredFieldValidator();
								rq.ControlToValidate = dt.DataEditor.Editor.ID;
								rq.EnableClientScript = enableClientScript;
								rq.CssClass = "umbracoAutoFormAlert";
								rq.Display = System.Web.UI.WebControls.ValidatorDisplay.Dynamic;
								string[] errorVars = {pt.Name, ""};
								rq.ErrorMessage = "<br/>" + umbraco.ui.Text("errorHandling", "errorMandatoryWithoutTab", errorVars, null);
								PHEditFields.Controls.Add(rq);
							} 
							catch (Exception valE)
							{
								System.Web.HttpContext.Current.Trace.Warn("contentControl", "EditorControl (" + dt.DataTypeName + ") does not support validation", valE);
							}
						}

						// RegExp Validation
						if (pt.ValidationRegExp != "") 
						{
							try 
							{
								System.Web.UI.WebControls.RegularExpressionValidator rv =new RegularExpressionValidator();
								rv.ControlToValidate = dt.DataEditor.Editor.ID;
								rv.ValidationExpression = pt.ValidationRegExp;
								rv.EnableClientScript = enableClientScript;
								rv.CssClass = "umbracoAutoFormAlert";
								rv.Display = System.Web.UI.WebControls.ValidatorDisplay.Dynamic;
								string[] errorVars = {pt.Name, ""};
								rv.ErrorMessage = "<br/>" + umbraco.ui.Text("errorHandling", "errorRegExpWithoutTab", errorVars, null);
								PHEditFields.Controls.Add(rv);
							} 
							catch (Exception valE)
							{
								System.Web.HttpContext.Current.Trace.Warn("contentControl", "EditorControl (" + dt.DataTypeName + ") does not support validation", valE);
							}

						}

						if (_showDescription && pt.Description != "") 
						{
							PHEditFields.Controls.Add(new LiteralControl("<br/><span class=\"umbracoAutoFormRowDescription\">" + pt.Description + "<br/></span>"));
						}

						PHEditFields.Controls.Add(new LiteralControl("</p>"));
			
					}
				}
			}
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{

		}
		#endregion

		protected void Button1_Click(object sender, System.EventArgs e)
		{
			if (Page.IsValid) 
			{
				umbraco.cms.businesslogic.web.Document d = new umbraco.cms.businesslogic.web.Document(_nodeId);
			
				if (!_editMode) 
				{
					string text = Title.Text;
					if (!_showTitle) 
					{
						try 
						{
							text = "RE: " + d.Text;
						} 
						catch {
							text = "Created by autoform " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();
						}
					}
					d = umbraco.cms.businesslogic.web.Document.MakeNew(text, new umbraco.cms.businesslogic.web.DocumentType(_nodeTypeId), new umbraco.BusinessLogic.User(_userId), _nodeId);
				} 
				else if (_showTitle)
					d.Text = Title.Text;

				// Save properties
				foreach (umbraco.interfaces.IDataType df in _dataFields)  
				{
					df.Data.PropertyId = d.getProperty(df.DataEditor.Editor.ID).Id;
					df.DataEditor.Save();

					if ((", " + _storeInCookie + ", ").IndexOf(", "+df.DataEditor.Editor.ID+", ") > -1) 
					{
						try 
						{
							System.Web.HttpCookie c = new System.Web.HttpCookie("umbAutoform_" + df.DataEditor.Editor.ID, df.Data.Value.ToString());
							c.Expires = DateTime.Now.AddYears(1);
							System.Web.HttpContext.Current.Response.Cookies.Add(c);
						} 
						catch (Exception ee)
						{
							Trace.Warn("Autoform", "Error storing value in cookie:", ee);
						}
					}
				}

				// Maybe save member info
				try 
				{
					if (_saveMemberIdAlias != "" && umbraco.cms.businesslogic.member.Member.GetCurrentMember() != null)
						d.getProperty(_saveMemberIdAlias).Value = umbraco.cms.businesslogic.member.Member.GetCurrentMember().Id;
				} 
				catch 
				{
					umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, d.User, d.Id, "Error saving member data. The specified Member Property alias ('" + _saveMemberIdAlias + "') does probably not exists on document type ('" + d.ContentType.Text + "').");
				}

				if (_publish) 
				{
					d.Publish(new umbraco.BusinessLogic.User(_userId));
					umbraco.library.PublishSingleNode(d.Id);
				} else
					umbraco.BusinessLogic.Actions.Action.RunActionHandlers(d, new umbraco.BusinessLogic.Actions.ActionToPublish());

				// Update UI
				if (_refreshToParent)
					Response.Redirect(umbraco.library.NiceUrl(_nodeId), true);
				else 
				{
					PanelInput.Visible = false;
					PanelThanks.Visible = true;
				}
			}
		}
	}
}
